package utils

import (
	"reflect"
	"time"
)

// AssignStruct 结构体赋值 value -> binding 传的都是pointer
func AssignStruct(binding interface{}, value interface{}) {
	bVal := reflect.ValueOf(binding).Elem() //获取reflect.Type类型
	vVal := reflect.ValueOf(value).Elem()   //获取reflect.Type类型
	vTypeOfT := vVal.Type()
	for i := 0; i < vVal.NumField(); i++ {
		// 在要修改的结构体中查询有数据结构体中相同属性的字段，有则修改其值
		name := vTypeOfT.Field(i).Name
		bField := bVal.FieldByName(name)
		vField := vVal.FieldByName(name)

		if ok := bField.IsValid(); ok {
			if bField.Kind() == vField.Kind() && vField.Type().String() == bField.Type().String() {
				bVal.FieldByName(name).Set(reflect.ValueOf(vVal.Field(i).Interface()))
			} else if vField.Type().String() == "utils.Datetime" {
				switch bField.Type().String() {
				case "string":
					bVal.FieldByName(name).Set(reflect.ValueOf(vVal.Field(i).Interface().(Datetime).String()))
				case "time.Time":
					t := vVal.Field(i).Interface().(Datetime).AsTime()
					bVal.FieldByName(name).Set(reflect.ValueOf(t))
				}
			} else if bField.Type().String() == "utils.Datetime" {
				switch vField.Type().String() {
				case "string":
					t, _ := time.Parse("2006-01-02 15:04:05", vVal.Field(i).String())
					bVal.FieldByName(name).Set(reflect.ValueOf(Datetime(t)))
				case "time.Time":
					bVal.FieldByName(name).Set(reflect.ValueOf(Datetime(vVal.Field(i).Interface().(time.Time))))
				}
			}
		}
	}
}
